/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ryopei.hatena;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.abdera.model.Entry;

/**
 *
 * @author ryohei
 */
public class SimpleEntry {
    private String editUrl;
    private String alternateUrl;
    private String date;
    private String entryId;
    private String title;
    
    private Set<String> categories = new HashSet<String>();
    private Set<String> initialCategories;

    private static Pattern TITLE_PATTERN = Pattern.compile("((\\[[^\\]]+\\])+)(.*)");

    SimpleEntry(Entry e) {
        Matcher m = TITLE_PATTERN.matcher(e.getTitle());
        Set<String> entryCategories = new HashSet<String>();
        this.editUrl = e.getEditLink().getHref().toASCIIString();
        this.alternateUrl = e.getAlternateLink().getHref().toASCIIString();

        String[] tmp = this.editUrl.split("/");
        this.date = tmp[tmp.length - 2];
        this.entryId = tmp[tmp.length - 1];

        if (m.matches()) {
            String s = m.group(1);
            this.title = m.group(3);

            boolean state = false;
            String buf = "";
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (!state) {
                    if (c == '[') {
                        buf = "";
                        state = true;
                    }
                }
                else if (state) {
                    if (c == ']') {
                        entryCategories.add(buf);
                        state = false;
                    }
                    else {
                        buf += c;
                    }
                }
            }

        }
        this.categories = entryCategories;
        this.initialCategories = new HashSet<String>(entryCategories);
    }

    public String getEditUrl() {
        return editUrl;
    }

    public String getAlternateUrl() {
        return alternateUrl;
    }

    public String getDate() {
        return date;
    }

    public String getTitle() {
        return title;
    }


    public String getEntryId() {
        return entryId;
    }

    public Set<String> getCategories() {
        return categories;
    }

    /**
     * カテゴリに変更があったかチェックする。
     * @return
     */
    public boolean isCategoryChanged() {
        return categories.equals(initialCategories);
    }

    /**
     * 初期化時のカテゴリに含まれているかチェックする。
     * @param category
     * @return
     */
    public boolean containsInitialCategories(final String category) {
        return this.initialCategories.contains(category);
    }

}
